<template>
	<view class="allImg">
		<!-- <AddModel ref="addSet" /> -->
		<view class="handleBtn">
			<button @click="handleUploadImg">上传图片</button>
			{{ cTimer }}
			<button @click="batchDel">批量删除选中的</button>
		</view>
		<view class="typeList">
			<view :class="item.type === nowType && 'cho'" v-for="item in classList" :key="item._id" @click="gotoPreview(item)">
				{{ item.name }}
			</view>

		</view>

		<view class="uni-pagination-box"><uni-pagination show-icon :page-size="pageSize" :current="pageCurrent" :total="total"
				@change="change" /></view>
		<div class="imgListBox">
			<div class="img" :class="getImgClass(item)" v-for="item in dataInfo" :key="item._id" @click="imgCho(item)">
				<img :src="imgUrl + item.thumb" class="tabImg" mode="aspectFill" />
			</div>
		</div>

	</view>
</template>

<script>
// import {
// 	dataInfo
// } from './tableData.js'

import { imgUrl } from '../../utils/public'
import {
	connectWallpaperTable,
	connectWallpaperTableTem,
	handleWallpaperTodo
} from '../../utils/uniCloudTodo'
const databaseCode = 'wallpaper'
// const databaseCode = 'wallpaperTem'

export const getTimerFromDate = (timestamp, dateFormat) => {
	const date = new Date(timestamp); // 将时间戳转换为Date对象
	const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
	const map = {
		'YYYY': date.getFullYear(), // 年份
		'MM': date.getMonth() + 1, // 月份
		'DD': date.getDate(), // 日期
		'HH': date.getHours(), // 小时
		'mm': date.getMinutes(), // 分钟
		'ss': date.getSeconds(), // 秒
		'EEEE': days[date.getDay()],
	};

	return dateFormat.replace(/YYYY|MM|DD|HH|mm|ss|EEEE/g, match => {
		return map[match].toString().padStart(2, '0');
	});
}
export default {
	components: {
	},
	data() {
		return {
			classList: [],
			nowType: '美女',
			imgChoList: [],
			searchVal: '',
			dataInfo: [],
			// 每页数据量
			pageSize: 20,
			// 当前页
			pageCurrent: 1,
			// 数据总量
			total: 1000,
			loading: false
		}
	},
	created() {
		this.getClassList()
		this.selectedIndexs = []
		this.getData(1)
	},
	computed: {
		isNotTem() {
			return databaseCode === 'wallpaper'
		},
		cTimer() {
			// return getTimerFromDate(new Date(), 'YYYY-MM-DD')
			return getTimerFromDate(new Date().getTime() + (24 * 60 * 60 * 1000), 'YYYY-MM-DD')
		},
		imgUrl() {
			return imgUrl
		}
	},
	methods: {
		async getClassList() {
			const db = uniCloud.database();
			const result = await db.collection('photoType').get();
			this.classList = result.result.data
		},
		gotoPreview(item) {
			this.nowType = item.type
			this.pageCurrent = 1
			this.dataInfo = []
			this.getData()
		},




		async batchDel(imgId) {
			const that = this
			uni.showModal({
				title: '提示',
				content: '确定要删除照片吗？',
				success: function (res) {
					if (res.confirm) {
						handle()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
			const handle = async () => {
				const isTemAction = uniCloud.database().collection('photoTypeList')

				this.imgChoList.forEach(async (item) => {
					await isTemAction.doc(item._id).remove()
				})
				this.getData(1)
			}
		},
		// 上传文件
		async uploadFiles(filePaths) {
			this.loading = true
			let imageList = []
			for (var i = 0; i < filePaths.length; i++) {
				const item = filePaths[i]
				const uploadTask = await uniCloud.uploadFile({
					filePath: item.filePath,
					cloudPathAsRealPath: true,
					cloudPath: `wallpaper/${item.name}`,
				});
				console.log(uploadTask, 'uploadTask');
				const fileId = uploadTask.fileID.split('/')
				imageList.push(`wallpaper/${fileId[fileId.length - 1]}`)
			}

			function getRandomArbitrary(min, max) {
				return Math.random() * (max - min) + min;
			}

			function getRandomNumber(min, max) {
				return Math.floor(getRandomArbitrary(min, max + 1));
			}
			const {
				isSift,
				tags,
				type
			} = this.$refs.addSet
			handleWallpaperTodo().batchUpload({
				databaseCode,
				imageList: imageList.map(path => {
					return {
						path,
						openid: 'orrOI671HjtuhoW3oCCkh4xNCoQ4',
						userId: 'map[$oid:6644cbe2ce5ec96267e82252]',
						showCount: getRandomNumber(450, 600),
						isSift,
						type,
						tags,
						createTime: new Date().getTime()
					}
				})
			}).then(res => {
				this.getData(1)
			})

		},
		handleUploadImg() {
			const that = this
			uni.chooseImage({
				count: 100,
				success: (res) => {
					const tempFilePaths = res.tempFiles.map(item => {
						return {
							name: item.name,
							filePath: item.path
						}
					})
					that.uploadFiles(tempFilePaths);
				}
			});
		},


		// 分页触发
		change(e) {
			this.pageCurrent = e.current
			this.getData(e.current)
		},
		// 搜索
		search() {
			this.getData(1, this.searchVal)
		},
		imgCho(item) {
			const isHaveInx = this.imgChoList.findIndex(cItem => cItem._id === item._id)
			if (isHaveInx === -1) {
				this.imgChoList.push(item)
			} else {
				this.imgChoList.splice(isHaveInx, 1)
			}
			console.log('this.imgChoList :>> ', this.imgChoList);
		},
		getImgClass(item) {
			const isHave = this.imgChoList.find(cItem => cItem._id === item._id)
			return isHave && 'imgCho'
		},
		// 获取数据
		getData(pageCurrent = this.pageCurrent, value = '') {
			this.loading = true
			this.pageCurrent = pageCurrent
			uni.showLoading({
				title: '加载中...'
			})

			uniCloud.database().collection('photoTypeList')
				.skip((this.pageCurrent - 1) * 10) //跳过已经查询的记录数量
				.limit(10) //每次请求10条记录
				.where(`type == '${this.nowType}'`) //只查询自己的订单
				.get()
				.then(res => {
					this.dataInfo = this.dataInfo.concat(res.result.data)
					console.log('dataInfo', this.dataInfo)
					this.loading = false
				})
				.catch(err => {
					console.log('查询失败', err)
				})
				.finally(() => {
					//无论成功或失败都执行
					uni.hideLoading()
				})



		},

	}
}
</script>

<style scoped lang="less">
.allImg {
	height: 500px;
	width: 100%;

	>.typeList {
		display: flex;

		>view {
			height: 30px;
			line-height: 30px;
			padding: 0 10px;
			border: 1px solid #000;
			text-align: center;
			margin-top: 10px;
			margin-left: 10px;
			cursor: pointer;
			background-color: #fff;
		}

		>.cho {
			background-color: green;
		}
	}

	.imgListBox {
		width: 100%;
		display: flex;
		flex-wrap: wrap;

		>.img {
			width: 320px;

			img {
				width: 100%;
			}
		}

		>.imgCho {
			border: 6px solid green;

			img {
				width: 100%;
			}
		}
	}
}

.uni-container {
	height: 500px;
}

/* #ifndef H5 */
/* page {
	padding-top: 85px;
} */
/* #endif */
.uni-group {
	display: flex;
	align-items: center;
}
</style>